<?php
declare (strict_types = 1);

namespace app\admin\controller\system;

use app\admin\BaseController;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Cache;
use think\Request;
use app\common\model\system\Menu as MenuModel;
use think\facade\Log;
use app\common\validate\Menu as MenuValidate;

class Menu extends BaseController
{
    //中间件
    protected $middleware = [
        'method:ajax' => ['only'=>['list','save','update','delete','batchDel','clear']],
    ];

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        return view('index');
    }

    /**
     * 菜单列表
     * @return \think\response\Json
     */
    public function list(){
        try{
            //获取列表数据
            $data = MenuModel::getListData($this->ruleWhere());


        }catch (\Exception $e){
            //系统错误
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg' => $e->getMessage(),
            ]);
        }

        //成功返回
        return json([
            'code'  => 0,
            'msg'=> '查询列表成功',
            'count' => $data['count'],
            'data'  => $data['data']
        ]);
    }


    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        return view('create',[
            'parents' => MenuModel::getParents()
        ]);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        try{
            //接收数据
            $data = $request->only(['name','route','icon','sort','parent_id','type']);
            $data['icon'] = $data['icon'] ? htmlspecialchars_decode($data['icon']) : '';

            //判断验证场景
            $scene = empty($data['parent_id']) ? 'top' : 'sub';
            //验证数据
            validate(MenuValidate::class)->scene($scene)->check($data);

            if ($this->getModel(MenuModel::class)->save($data) === false){
                throw new Exception('新建菜单失败.');
            }

            return json([
                'code' => 0,
                'msg' => '添加成功.'
            ]);

        }catch (ValidateException $e){
            return json([
                'code' => 1,
                'msg' => $e->getMessage()
            ]);
        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg' => $e->getMessage()
            ]);
        }
    }


    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit(int $id)
    {
        return view('edit',[
            'parents' => MenuModel::getParents(),
            'model' => $this->getModel(MenuModel::class, $id)
        ]);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, int $id)
    {
        try{
            //接收数据
            $data = $request->only(['name','route','icon','sort','parent_id','type']);
            $data['icon'] = $data['icon'] ? htmlspecialchars_decode($data['icon']) : '';
            //判断验证场景
            $scene = empty($data['parent_id']) ? 'top' : 'sub';

            //验证数据
            validate(MenuValidate::class)->scene($scene)->check(array_merge($data,['id'=>$id]));

            if ($this->getModel(MenuModel::class, $id)->save($data) === false){
                throw new Exception('编辑失败.');
            }

            return json([
                'code' => 0,
                'msg' => '编辑成功.'
            ]);

        }catch (ValidateException $e){
            return json([
                'code' => 1,
                'msg' => $e->getMessage()
            ]);
        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete(int $id)
    {
        try{
            $model = $this->getModel(MenuModel::class, $id);
            if ($model->delete() === false){
                throw new Exception('删除失败.');
            }

            return json([
                'code' => 0,
                'msg' => '删除成功.'
            ]);

        }catch (\Exception $e){
            return json([
                'code' => 1,
                'msg' => $e->getMessage()
            ]);
        }

    }

    /**
     * 批量删除
     *
     * @return \think\Response
     */
    public function batchDel()
    {
        try{
            $ids = explode(',', trim(request()->param('ids'),','));

            if($this->batchRule(MenuModel::class, (array) $ids) &&
                MenuModel::destroy($ids) === false )
            {
                throw new Exception('批量删除失败.');
            }
            return json([
                'code' => 0,
                'msg' => '批量删除成功.'
            ]);
        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg' => $e->getMessage()
            ]);
        }


    }

    /**
     * 删除菜单缓存
     */
    public function clear(){

        Cache::delete(MenuModel::CACHE_ADMIN_MENU);
        Cache::delete(MenuModel::CACHE_INDEX_MENU);
        return json([
            'code' => 0,
            'msg' => '删除菜单缓存成功.'
        ]);
    }
}
